//
//  GSSearchViewController.m
//  GameSky
//
//  Created by lanou on 16/1/13.
//  Copyright © 2016年 NiRongfei. All rights reserved.
//

#import "GSSearchViewController.h"
#import "GSSubscribeViewController_Add_Topic_Details.h"
#import "GSSubscribeViewController_Add_Topic_Cell.h"
#import "GSSearchViewController_TableView.h"
#import "GSSearchViewNavigationView.h"
#import "GSSearch_threeImageCell.h"
#import "GSSearch_Cell.h"
#import "GSSearch_Model.h"
#import "GSSubscrebe_Add_Topic.h"
#import "GSArticleViewController.h"
#import "GSStrategyDetailViewController.h"
@interface GSSearchViewController () <UITextFieldDelegate,UITableViewDataSource,UITableViewDelegate,UIScrollViewDelegate>
// 搜索 框
@property (nonatomic, strong) UIView *searchView;
// 导航View
@property (nonatomic, strong) UIView *navigationView;
// 输入框
@property (nonatomic, strong) UITextField *textField;


// 展示页面
   // scrollView
@property (nonatomic, strong) UIScrollView *scrollView;
   // tableView--News 新闻
@property (nonatomic, strong) GSSearchViewController_TableView *tableView_News;
   // tableView--Strategy 攻略
@property (nonatomic, strong) GSSearchViewController_TableView *tableView_Strategy;
   // tableView--Subscribe 订阅
@property (nonatomic, strong) GSSearchViewController_TableView *tableView_Subscribe;

/**
 * 未搜索
 */

// 数据源  (装载 string)
@property (nonatomic, strong) NSMutableArray *listArray;
// 保存订阅 的 数据源(装载 model)
@property (nonatomic, strong) NSMutableArray *subscribeArray;

// 界面刚 生成时,应 展示 type种类中的一种 数据
@property (nonatomic, strong) NSString *typeString;
// 数据请求时, type 种类(新闻or攻略)
@property (nonatomic, strong) NSArray *typeArray;
// 保存  button的指针 (铺设为搜索界面时,所需的button)
@property (nonatomic, strong) UIButton *button;


/**
 * 搜索时
 */
// 展示view
@property (nonatomic, strong) GSSearchViewNavigationView *searchNavigationView;

/**
 * 搜索
 */
// 搜索 -- 新闻 数据源
@property (nonatomic, strong) NSMutableArray *searchArray_News;
// 搜搜 -- 攻略 数据源
@property (nonatomic, strong) NSMutableArray *searchArray_Strategy;
// 搜索 -- 订阅 数据源
@property (nonatomic, strong) NSMutableArray *searchArray_Subscribe;
// 判断 是否  已经 搜索过了
@property (nonatomic, assign) BOOL isSearched;
// 搜索数据  ,起始  index----新闻
@property (nonatomic, strong) NSNumber *startIndex_News;
// 搜索数据, 起始  index ------攻略
@property (nonatomic, strong) NSNumber *startIndex_Strategy;
// 保存 搜索 关键字符串
@property (nonatomic, strong) NSString *searchingString;

/**
 *  数据库
 */
@property (nonatomic, strong) FMDatabase *db;
// 数据库 里的数据
@property (nonatomic, strong) NSMutableArray *dbArray;
@end

@implementation GSSearchViewController
- (void)viewWillAppear:(BOOL)animated{
    self.navigationController.navigationBarHidden = NO;
    self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:155/255.0 green:37/255.0 blue:34/255.0 alpha:1.0];
    self.navigationItem.title = @"搜索";
    
    self.navigationController.navigationBar.translucent = NO;
    
    //  获取 数据库的数据
    [self getDataArrayByDB];
    // 刷新 订阅界面的 数据
    [self.tableView_Subscribe reloadData];
    
    self.tabBarController.tabBar.hidden = YES;
}
- (void)viewWillDisappear:(BOOL)animated{
    self.tabBarController.tabBar.hidden = NO;
    self.navigationController.navigationBarHidden = YES;
}
#pragma mark-------------------视图加载完成-----------------
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor brownColor];
// 初始化 数据源数据 ----未搜索
    self.listArray = [NSMutableArray array];
    self.subscribeArray = [NSMutableArray array];
// 设置标题
    self.navigationItem.title = @"搜索";
// 添加搜索框
    [self addSearchView];
// 创建导航View
    [self createNavigationView];

    
    
    // 数据请求,请求参数 type数组,初始化
    self.typeArray = @[@"news",@"strategy"];


// 添加scrollView
    [self addScrollView];
// scrollView添加子视图
    [self addSubViewOnScrollView];
    
// 初始化 typeString
    if (self.number != 1002) {
        self.typeString = self.typeArray[self.number - 1000];
    }
// 展示初始界面
    [self setUpDataWithTag:self.number];
}
#pragma mark-------------------添加搜索框--------------------
- (void)addSearchView{
//  创建  searchView
    self.searchView = [[UIView alloc] initWithFrame:CGRectMake(8, 10, kScreenWidth - 16, 36)];
    _searchView.layer.cornerRadius = 10;
    _searchView.backgroundColor = [UIColor whiteColor];
    _searchView.layer.borderColor = [UIColor grayColor].CGColor;
    // 添加 放大镜 图片
    UIImageView *imageV = [[UIImageView alloc] initWithFrame:CGRectMake(10, 0, 20, 36)];
    [imageV setAutoresizesSubviews:YES];

    imageV.image = [UIImage imageNamed:@"common_Icon_Search_20x20_UIMode_Day@2x"];
    [_searchView addSubview:imageV];
    // 添加 输入框
    self.textField = [[UITextField alloc] initWithFrame:CGRectMake(imageV.right + 20, 0, kScreenWidth - 16 - imageV.right - 20, 36)];
    _textField.delegate = self;
    _textField.placeholder = @"输入搜索内容";
    _textField.clearButtonMode = UITextFieldViewModeWhileEditing;
    [_searchView addSubview:_textField];
    [self.view addSubview:_searchView];
}
#pragma mark--------------------创建导航View-------------
- (void)createNavigationView{
    self.navigationView = [[UIView alloc] initWithFrame:CGRectMake(0, 66, kScreenWidth, 42)];
    _navigationView.backgroundColor = [UIColor whiteColor];
    NSArray *titleArray = @[@"新闻",@"攻略",@"订阅"];
    // 循环创建Button
    for (int i = 0; i < 3; i++) {
        UIButton *button = [UIButton buttonWithType:(UIButtonTypeCustom)];
        if (i == self.number - 1000) {
            button.selected = YES;
        }
        button.frame = CGRectMake(0 + (i * kScreenWidth / 3), 0, kScreenWidth / 3, 42);
        button.tag = 1000 + i;
        [button setTitle:titleArray[i] forState:(UIControlStateNormal)];
        [button setTitleColor:[UIColor grayColor] forState:(UIControlStateNormal)];
        [button setTitleColor:[UIColor redColor] forState:(UIControlStateSelected)];
        [button addTarget:self action:@selector(buttonClick:) forControlEvents:(UIControlEventTouchUpInside)];
        [_navigationView addSubview:button];
    }
    [self.view addSubview:_navigationView];
}
#pragma mark--------------------button点击方法-----------
- (void)buttonClick:(UIButton *)button{
    // 遍历button  改变 button的 选中状态
    for (UIButton *oneButton in _navigationView.subviews) {
        if (oneButton.tag == button.tag) {
           oneButton.selected = YES;
// 改变  scrollView的 偏移量
            [_scrollView setContentOffset:CGPointMake((oneButton.tag - 1000) * kScreenWidth, 0) animated:YES];
            //请求 数据,显示
            if (button.tag != 1002) {
                self.typeString = _typeArray[button.tag - 1000];
            }
            [self setUpDataWithTag:button.tag];
            
        }else{
            oneButton.selected = NO;
        }
    }
}
#pragma mark--------------搜索 订阅界面 数据请求------------
- (void)setUpDataSubscribe:(NSString *)searchString{
    NSDictionary *dictionary = @{@"request":@{@"type":@1}};
    [GSNetworkManager requestWithUrlStr:@"http://appapi2.gamersky.com/v2/subscribe" paraDict:dictionary method:POST success:^(NSURLResponse *response, NSData *data) {
        if (data) {
            NSMutableDictionary *dicData = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers) error:nil];
            // 获取所需数据
            NSArray *array = dicData[@"result"];
            for (NSDictionary *oneDic in array) {
                GSSubscrebe_Add_Topic *model = [[GSSubscrebe_Add_Topic alloc] init];
                [model setValuesForKeysWithDictionary:oneDic];
                [_subscribeArray addObject:model];
            }
            
            [self.searchArray_Subscribe removeAllObjects];
            for (GSSubscrebe_Add_Topic *model in self.subscribeArray) {
                if ([model.sourceName rangeOfString:searchString].location != NSNotFound) {
                    [self.searchArray_Subscribe addObject:model];
                }
                
            }
            [self.tableView_Subscribe.mj_header endRefreshing];
            [self.tableView_Subscribe reloadData];
        }
    } failure:^(NSError *error) {
        NSLog(@"请求出错");
    }];
}
#pragma mark---------------解析数据(未搜索)----------------------
- (void)setUpDataWithTag:(NSInteger)tag{
    // 获取 tableView
      GSSearchViewController_TableView *tableView = (GSSearchViewController_TableView *)[_scrollView viewWithTag:tag];
    // 判断 boxView 是否已经  有数据 展示了
       if (tableView.boxView.subviews.count == 0) {
    // 没有 则  展示数据
    if (tag == 1002) {
        // 当 展示 订阅 页面时, 展示的数据 是 订阅 详情 里的数据
        //重新请求
        NSDictionary *dictionary = @{@"request":@{@"type":@1}};
        [GSNetworkManager requestWithUrlStr:@"http://appapi2.gamersky.com/v2/subscribe" paraDict:dictionary method:POST success:^(NSURLResponse *response, NSData *data) {
            if (data) {
            NSMutableDictionary *dicData = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers) error:nil];
            // 获取所需数据
            NSArray *array = dicData[@"result"];
                [self.listArray removeAllObjects];
            for (NSDictionary *oneDic in array) {
                [_listArray addObject:oneDic[@"sourceName"]];
            }
                int num = 0;
                // 调用 方法  ,展示 button
                // 改变 boxView的frame
                CGFloat height = [self addButtonsWith:num tableView:tableView];
                tableView.boxView.contentSize = CGSizeMake(tableView.boxView.width, height + 30);
                
            }
        } failure:^(NSError *error) {
            NSLog(@"请求出错");
        }];
 
    }else{
        // 单独的 数据请求, 请求, 新闻 和 攻略 页面数据,并展示
    NSDictionary *dic = @{@"request":@{@"searchType":_typeString}};
    [GSNetworkManager requestWithUrlStr:Subscribe_SearchHotDict paraDict:dic method:(POST) success:^(NSURLResponse *response, NSData *data) {
            if (data) {
                NSMutableDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers) error:nil];
                // 获取所需数据
                self.listArray = dic[@"result"];
                int num = 0;
                // 数据请求完成, 应展示,
                // 调用 方法,  添加 展示的 button
                
                // 改变 boxView的frame
          CGFloat height = [self addButtonsWith:num tableView:tableView];
//                CGRect temp = tableView.boxView.frame;
//                temp.size.height = height;
//                tableView.boxView.frame = temp;
                tableView.boxView.contentSize = CGSizeMake(tableView.boxView.width, height + 30);
                
            }
     } failure:^(NSError *error) {
      }];
    }
  }
}
#pragma mark---------------数据请求(搜索)----------------------
// news  界面数据请求
- (void)setUpNewsDataBySearchingWithString:(NSString *)searchString{
// 构建参数字典
    NSDictionary *dic_news = @{@"request":@{@"searchType":@"news",
                                            @"searchKey":searchString,
                                            @"pageIndex":_startIndex_News,
                                            @"elementsCountPerPage":@20
                                            }
                               };
    // 请求数据
[GSNetworkManager requestWithUrlStr:Subscribe_SearchTwoSearch paraDict:dic_news method:(POST) success:^(NSURLResponse *response, NSData *data) {
    NSMutableDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers) error:nil];
    if (data) {
     // 获取  所需 数据
        if ([_startIndex_News  isEqual: @1]) {
            [self.searchArray_News removeAllObjects];
        }
        
                // 数据源 数组装载  model
        NSArray *array = dic[@"result"];
        for (NSDictionary *oneDic in array) {
            GSSearch_Model *model = [[GSSearch_Model alloc] init];
            [model setValuesForKeysWithDictionary:oneDic];
            [self.searchArray_News addObject:model];
        }
        // 结束 下拉 上提 刷新
        [self.tableView_News.mj_header endRefreshing];
        [self.tableView_News.mj_footer endRefreshing];
        [self.tableView_News reloadData];
    }
} failure:^(NSError *error) {
    
}];
}
// 攻略 界面数据请求
- (void)setUpStrategyDataBySearchingWithString:(NSString *)searchString{
    // 构建参数字典
    NSDictionary *dic_strategy = @{@"request":@{@"searchType":@"strategy",
                                            @"searchKey":searchString,
                                            @"pageIndex":_startIndex_Strategy,
                                            @"elementsCountPerPage":@20
                                            }
                               };
    // 请求数据
    [GSNetworkManager requestWithUrlStr:Subscribe_SearchTwoSearch paraDict:dic_strategy method:(POST) success:^(NSURLResponse *response, NSData *data) {
        NSMutableDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers) error:nil];
        if (data) {
            // 获取  所需 数据
            if ([_startIndex_Strategy isEqual: @1]) {
                [self.searchArray_Strategy removeAllObjects];
            }
            // 数据源 数组装载  model
            NSArray *array = dic[@"result"];
            for (NSDictionary *oneDic in array) {
                GSSearch_Model *model = [[GSSearch_Model alloc] init];
                [model setValuesForKeysWithDictionary:oneDic];
                [self.searchArray_Strategy addObject:model];
            }
            // 结束刷新
            [self.tableView_Strategy.mj_header endRefreshing];
            [self.tableView_Strategy.mj_footer endRefreshing];
            [self.tableView_Strategy reloadData];
        }
    } failure:^(NSError *error) {
        
    }];
}
// 订阅 界面数据请求
- (void)setUpSubscribeDataBySearchingWithString:(NSString *)searchString{
    if (self.subscribeArray.count == 0) {
        [self setUpDataSubscribe:searchString];
    }else{
        [self.searchArray_Subscribe removeAllObjects];

        for (GSSubscrebe_Add_Topic *model in self.subscribeArray) {
            // 判断是否 包含所 搜寻的关键字
            // 清空数组
            if ([model.sourceName rangeOfString:searchString].location != NSNotFound) {
                [self.searchArray_Subscribe addObject:model];
            }
        }
        [self.tableView_Subscribe.mj_header endRefreshing];
    [self.tableView_Subscribe reloadData];
    }
}
#pragma mark---------------自适应宽度---------------------
//  此方法 是通过 字符串, 获取 label的宽高,  从而获取 button的 宽高
- (UIButton *)autoFitWithString:(NSString *)string{
    UIButton *button = [UIButton buttonWithType:(UIButtonTypeCustom)];
    button.layer.borderWidth = 1;
    button.layer.borderColor = [UIColor grayColor].CGColor;
    // label
    UILabel *label = [[UILabel alloc] init];
    label.font = [UIFont systemFontOfSize:16];
    CGRect temp = [string boundingRectWithSize:CGSizeMake(kScreenWidth, CGFLOAT_MAX) options:(NSStringDrawingUsesLineFragmentOrigin) attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:16]} context:nil];
    // 自适应宽度
    label.frame = CGRectMake(8, 8, temp.size.width, 20);
    // 设置 文字
    label.text = string;
    // 通过label  设置button的宽高
    button.frame = CGRectMake(0, 0, label.width + 16, label.height + 16);
    [button addSubview:label];
    return button;
}
#pragma mark---------------添加button------------------
// 返回 最后添加的一个button的bottom
- (CGFloat)addButtonsWith:(int)num tableView:(GSSearchViewController_TableView *)tableView{
    // button的 添加方式:
    // 当 添加 时, 应 判断  下一个 button 是否可以在同一行添加,若可以, 则添加
    // 不可以 ,则 下一行 添加
    //  方法 设置了  计数
    // 当  计数  为  数据源数组的个数, 则说明 添加 完毕, 则 跳出循环
    for (int i = 0; i < 20; i++) {
            for (int j = 0; j < 10; j++) {
                UIButton *button = nil;
                if (j == 0) {
                    // 固定第一个button
                    button = [self autoFitWithString:_listArray[num]];
                    CGRect temp = button.frame;
                    temp.origin.x = 10;
                    temp.origin.y = 10 + (i * (36 + 10));
                    button.frame = temp;
                }else{
                    // 利用上一个button ,固定frame
                    button = [self autoFitWithString:_listArray[num]];
                    CGRect temp = button.frame;
                    temp.origin.x = self.button.right + 10;
                    temp.origin.y = self.button.top;
                    button.frame = temp;
                }
                // 添加button
                self.button = button;
                // 添加方法, 用来搜索
                [button addTarget:self action:@selector(hotWordButtonAciton:) forControlEvents:(UIControlEventTouchUpInside)];
                num++;
                [tableView.boxView addSubview:button];
                // 如果 所有 数据已经展示,则 break
                if (num == _listArray.count) {
                    
                    return button.bottom;
                }else{
                    // 判断当前行能否显示当前与下一个button
                    UIButton *buttonNext = [self autoFitWithString:_listArray[num]];
                    if (button.right + 10 + buttonNext.width < kScreenWidth - 20) {
                    }else{
                        break;
                    }
                }
            }
        }
    return 0;
}

#pragma mark---------------添加scrollView-------------
- (void)addScrollView{
// 创建
    self.scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, _navigationView.bottom, kScreenWidth, kScreenHeight - _navigationView.bottom)];
    _scrollView.backgroundColor = [UIColor whiteColor];
// 回弹
    _scrollView.bounces = NO;
// 翻页
    _scrollView.pagingEnabled = YES;
// 轨迹线
    _scrollView.alwaysBounceHorizontal = YES;
    _scrollView.alwaysBounceVertical = NO;
// 代理
    _scrollView.delegate = self;
// 滑动区域
    _scrollView.contentSize = CGSizeMake(kScreenWidth * 3, _scrollView.height);
// 设定初始位置
    [_scrollView setContentOffset:CGPointMake((self.number - 1000) * kScreenWidth, 0) animated:NO];
    [self.view addSubview:_scrollView];
}
#pragma mark---------------scrollView协议---------------
// 滑动结束,改变  button的 选中状态
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
// 判断 滑动的视图
    if ([scrollView isEqual:_scrollView]) {
    CGFloat x = scrollView.contentOffset.x /  kScreenWidth;
    NSInteger num = (NSInteger)1000 + x;
    // 取出对应的button, 重新 执行一边,button点击方法
    UIButton *button = (UIButton *)[_navigationView viewWithTag:num];
    [self buttonClick:button];
    }
}
#pragma mark---------------ScrollView添加子视图-------------
- (void)addSubViewOnScrollView{
    for (int i = 0; i < 3; i++) {
        GSSearchViewController_TableView *tableView = [[GSSearchViewController_TableView alloc] initWithFrame:CGRectMake(0 + (i * kScreenWidth), 0, _scrollView.width, _scrollView.height) style:(UITableViewStylePlain)];
        tableView.tag = 1000 + i;
// 修改 cell的 分离 样式
        tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        tableView.delegate = self;
        tableView.rowHeight = kScreenHeight / 8;
        tableView.dataSource = self;
        [_scrollView addSubview:tableView];
    }
// 搜索后-------新闻 界面
    self.tableView_News = (GSSearchViewController_TableView *)[_scrollView viewWithTag:1000];
    //self.tableView_News.backgroundColor = [UIColor redColor];
    // 添加下拉刷新
    _tableView_News.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        self.startIndex_News = @1;
        [self setUpNewsDataBySearchingWithString:self.searchingString];
    }];
    // 添加上提加载
    _tableView_News.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        int num = [self.startIndex_News intValue];
        num += 1;
        self.startIndex_News = [NSNumber numberWithInt:num];
        [self setUpNewsDataBySearchingWithString:self.searchingString];
    }];
    
    

    
// 搜索后--------攻略界面
    self.tableView_Strategy = (GSSearchViewController_TableView *)[_scrollView viewWithTag:1001];
    //_tableView_Strategy.backgroundColor = [UIColor magentaColor];

    // 添加 下拉刷新
    _tableView_Strategy.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        self.startIndex_Strategy = @1;
        [self setUpStrategyDataBySearchingWithString:self.searchingString];
    }];
    // 添加 上提加载
    _tableView_Strategy.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        int num = [self.startIndex_Strategy intValue];
        num += 1;
        self.startIndex_Strategy = [NSNumber numberWithInt:num];
        [self setUpStrategyDataBySearchingWithString:self.searchingString];
    }];
    
    
// 搜索后----------订阅界面
    self.tableView_Subscribe = (GSSearchViewController_TableView *)[_scrollView viewWithTag:1002];
    
    //_tableView_Subscribe.backgroundColor = [UIColor purpleColor];
    
    UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0,kScreenWidth, 48)];
    footerView.backgroundColor = [UIColor grayColor];
    UILabel *footLabel = [[UILabel alloc] initWithFrame:CGRectMake(6, 6, kScreenWidth - 12, 36)];
    footLabel.backgroundColor = [UIColor whiteColor];
    [footerView addSubview:footLabel];
    footLabel.textColor = [UIColor redColor];
    footLabel.textAlignment = NSTextAlignmentCenter;
    footLabel.text = @"没有更多内容了";
    self.tableView_Subscribe.tableFooterView = footerView;
    // 交换 视图位置
    [self.tableView_Subscribe exchangeSubviewAtIndex:1 withSubviewAtIndex:2];
    
    // 添加下拉刷新
    _tableView_Subscribe.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self setUpSubscribeDataBySearchingWithString:self.searchingString];
    }];
}
#pragma mark--------------从数据库里获取数据------------
- (NSMutableArray *)dbArray{
    if (!_dbArray) {
        _dbArray = [NSMutableArray array];
    }
    return _dbArray;
}
- (void)getDataArrayByDB{
    // 从数据库里获取 数据
    // 打开数据库
    NSString *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject;
    // 拼接路径
    NSString *pathString = [[path stringByAppendingPathComponent:@"data"]stringByAppendingPathComponent:@"GSDataBase.db"];
    _db = [FMDatabase databaseWithPath:pathString];
    if (![_db open]) {
        NSLog(@"数据打开失败");
    }
    // 清空数组
    [self.dbArray removeAllObjects];
    
    FMResultSet *resultSet = [_db executeQuery:@"select * from SubscribeList"];
    while ([resultSet next]) {
        NSString *nodeIds = [resultSet stringForColumn:@"nodeIds"];
        NSNumber *cnt = [NSNumber numberWithInt:[resultSet intForColumn:@"cnt"]];
        NSString *sourceName = [resultSet stringForColumn:@"sourceName"];
        NSData *imageData = [resultSet dataForColumn:@"imageData"];
        GSSubscrebe_Add_Topic *model = [[GSSubscrebe_Add_Topic alloc] init];
        model.sourceName = sourceName;
        model.imageModel = [UIImage imageWithData:imageData];
        model.sourceId = nodeIds;
        model.cnt = cnt;
        [self.dbArray addObject:model];
    }
    
}

#pragma mark--------------tabview协议------------------
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (tableView == self.tableView_News) {
        return _searchArray_News.count;
    }else if (tableView == self.tableView_Strategy){
        return _searchArray_Strategy.count;
    }else{
        return _searchArray_Subscribe.count;
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
// 新闻
    if (tableView.tag == self.tableView_News.tag) {
    //取出model,判别 属性, 确定cell
        GSSearch_Model *model = self.searchArray_News[indexPath.row];
        if (model.thumbnailURLs.count == 3) {
            // 三图 cell
            static NSString *three = @"threeImage";
            GSSearch_threeImageCell *cell = [tableView dequeueReusableCellWithIdentifier:three];
            if (cell == nil) {
                cell = [[GSSearch_threeImageCell alloc] initWithStyle:(UITableViewCellStyleSubtitle) reuseIdentifier:three];
            }
            
            cell.model = model;
            return cell;
        }else{
        // 单图  或者没图cell
        static NSString *identifier = @"cell";
            GSSearch_Cell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
            if (cell == nil) {
                cell = [[GSSearch_Cell alloc] initWithStyle:(UITableViewCellStyleSubtitle) reuseIdentifier:identifier];
            }
            cell.model = model;
            return cell;
        }
    }else if (tableView.tag == self.tableView_Strategy.tag){
// // 攻略
        GSSearch_Model *model = self.searchArray_Strategy[indexPath.row];
        if ([model.contentType isEqualToString:@"strategylist"] && [model.type isEqualToString:@"game"]) {
            static NSString *strategylist = @"strategylist";
            GSSubscribeViewController_Add_Topic_Cell *cell = [tableView dequeueReusableCellWithIdentifier:strategylist];
            if (cell == nil) {
                cell = [[GSSubscribeViewController_Add_Topic_Cell alloc] initWithStyle:(UITableViewCellStyleSubtitle) reuseIdentifier:strategylist];
            }
 // 判断数据库是否有数据

            cell.searchModel = model;
            return cell;
        }else{
        static NSString *strategy = @"strategy";
            GSSearch_Cell *cell = [tableView dequeueReusableCellWithIdentifier:strategy];
            if (cell == nil) {
                cell = [[GSSearch_Cell alloc] initWithStyle:(UITableViewCellStyleSubtitle) reuseIdentifier:strategy];
            }
            
            cell.model = model;
            return cell;
        }
        
    }else{
// 订阅
        static NSString *subscribe = @"subscribe";
        GSSubscribeViewController_Add_Topic_Cell *cell = [tableView dequeueReusableCellWithIdentifier:subscribe];
        if (cell == nil) {
            cell = [[GSSubscribeViewController_Add_Topic_Cell alloc] initWithStyle:(UITableViewCellStyleSubtitle) reuseIdentifier:subscribe];
        }
        GSSubscrebe_Add_Topic *model = self.searchArray_Subscribe[indexPath.row];
        
        // 初始化 订阅状态
        model.isSubscribe = NO;
        // 判断 是否  已经保存到 数据库当中,改变 订阅按钮的样式
        NSString *sourceIdString = [NSString stringWithFormat:@"%@",model.sourceId];
        for (GSSubscrebe_Add_Topic *modelDB in _dbArray) {
            if ([sourceIdString isEqualToString:modelDB.sourceId]) {
                model.isSubscribe = YES;
            }
        }
        cell.subscibeButton.userInteractionEnabled = NO;
        cell.model = model;
        return cell;
    }
}
// cell 高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (tableView.tag == self.tableView_News.tag) {
        //取出model,判别 属性, 确定cell
        GSSearch_Model *model = self.searchArray_News[indexPath.row];
        if (model.thumbnailURLs.count == 3) {
            return kScreenHeight / 4;
        }else{
            // 单图  或者没图cell
            return kScreenHeight / 8;
        }
    }else if (tableView.tag == self.tableView_Strategy.tag){
        return kScreenHeight / 8;
    }else{
        // 订阅
        return kScreenHeight / 8;
    }
}
// cell点击方法
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
// 新闻跳转
    if (tableView.tag == self.tableView_News.tag) {
        GSArticleViewController *articleView = [[GSArticleViewController alloc] init];
        GSSearch_Model *model = self.searchArray_News[indexPath.row];
        articleView.contentID = model.contentId;
        [self.navigationController pushViewController:articleView animated:YES];
        
    }else if (tableView.tag == self.tableView_Strategy.tag){
// 攻略跳转
        GSSearch_Model *model = self.searchArray_Strategy[indexPath.row];
        if ([model.contentType isEqualToString:@"strategylist"] && [model.type isEqualToString:@"game"]) {
            // 有  订阅 按钮 样式的 cell跳转
            GSStrategyDetailViewController *strategyDetailVC = [[GSStrategyDetailViewController alloc] init];
            GSStrategyMainModel *mainModel = [[GSStrategyMainModel alloc] init];
            mainModel.specialID = model.contentId;
            strategyDetailVC.model = mainModel;
            
            [self.navigationController pushViewController:strategyDetailVC animated:YES];
            
            
        }else{
        // 无订阅按钮样式的cell   跳转到  webView
            GSArticleViewController *articleView = [[GSArticleViewController alloc] init];
            GSSearch_Model *model = self.searchArray_News[indexPath.row];
            articleView.contentID = model.contentId;
            [self.navigationController pushViewController:articleView animated:YES];
        }
    }else{
// 订阅 页面 跳转
        // 获取model
        GSSubscrebe_Add_Topic *model = self.searchArray_Subscribe[indexPath.row];
        
        // 创建 请求字典, 添加 相应键值对, 传给下一个界面,方便 请求数据
        NSDictionary *dic = @{@"request":@{@"parentNodeId":@"dingYue",
                                           @"nodeIds":model.sourceId,
                                           @"type":@"dingyueList",
                                           @"pageIndex":@1,
                                           @"elementsCountPerPage":@20}
                              };
        // 创建,并赋属性
        GSSubscribeViewController_Add_Topic_Details *detailsVC = [[GSSubscribeViewController_Add_Topic_Details alloc] init];
        detailsVC.dic = dic;
        detailsVC.isSubscribe = model.isSubscribe;
        
        detailsVC.model = model;
        
        GSSubscribeViewController_Add_Topic_Cell *cell = [self.tableView_Subscribe cellForRowAtIndexPath:indexPath];
        NSData *imageData = UIImagePNGRepresentation(cell.imageV.image);
        detailsVC.imageData = imageData;
        // 跳转
        [self.navigationController pushViewController:detailsVC animated:YES];
}
}

#pragma mark--------------------搜索后 数据源数组懒加载------------------------
// news
- (NSMutableArray *)searchArray_News{
    if (!_searchArray_News) {
        _searchArray_News = [NSMutableArray array];
    }
    return _searchArray_News;
}
- (NSMutableArray *)searchArray_Strategy{
    if (!_searchArray_Strategy) {
        _searchArray_Strategy = [NSMutableArray array];
    }
    return _searchArray_Strategy;
}
- (NSMutableArray *)searchArray_Subscribe{
    if (!_searchArray_Subscribe) {
        _searchArray_Subscribe = [NSMutableArray array];
    }
    return _searchArray_Subscribe;
}
#pragma mark--------------------热词搜索按钮 实现---------------
- (void)hotWordButtonAciton:(UIButton *)button{
    for (UILabel *label in button.subviews) {
        if ([label isMemberOfClass:[UILabel class]]) {
            // 设置 搜索的字为 点击的热词
            _textField.text = label.text;
            // 搜索
            [self hideBoxViewToSearchDataWithSearchString:_textField.text];
        }
    }
}
#pragma mark--------------------隐藏 boxView,开始搜索数据-----------
- (void)hideBoxViewToSearchDataWithSearchString:(NSString *)searchString{
    // 隐藏  tableView上的boxView
    //  判断是否 搜索过了,  如果 搜过了, 那就没必要再移除一边(已经 移除一遍了) boxView了
    if (self.isSearched == NO) {
        for (GSSearchViewController_TableView *tableView in _scrollView.subviews) {
            if ([tableView isMemberOfClass:[GSSearchViewController_TableView class]]) {
                // 当boxVieW隐藏时, 父视图tableView 应该可以滑了
                tableView.scrollEnabled = YES;
                tableView.boxView.hidden = YES;
            }
        }
        self.isSearched = YES;
    }
    // 加载数据
    self.startIndex_News = @1;
    self.startIndex_Strategy = @1;
    // 清空 搜索 后 装载数据的数组
    [self.searchArray_News removeAllObjects];
    [self.searchArray_Strategy removeAllObjects];
    [self.searchArray_Subscribe removeAllObjects];
    // 保存  搜索 字符串(刷新时需要此数据, 用指针保存)
    self.searchingString = searchString;
    
    [self setUpNewsDataBySearchingWithString:searchString];
    [self setUpStrategyDataBySearchingWithString:searchString];
    [self setUpSubscribeDataBySearchingWithString:searchString];

}
#pragma mark--------------------textField代理-----------------
- (BOOL)textFieldShouldReturn:(UITextField *)textField{

    if (textField.text.length != 0) {
// 将 搜索的 关键字 写入 数据库
        // 判断 之前 是否 搜索过,如果搜索过,则不保存到数据库
        NSString *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject;
        // 拼接路径
        NSString *pathString = [[path stringByAppendingPathComponent:@"data"]stringByAppendingPathComponent:@"GSDataBase.db"];
        _db = [FMDatabase databaseWithPath:pathString];
        if (![_db open]) {
            NSLog(@"数据打开失败");
        }
        // 获取 数据库里的数据
        NSMutableArray *dbArray = [NSMutableArray array];
        // 取出 存储的 数据 展示
        FMResultSet *resultSet = [_db executeQuery:@"select * from SearchHistoryList"];
        while ([resultSet next]) {
            NSString *history = [resultSet stringForColumn:@"history"];
            [dbArray addObject:history];
        }
        // 遍历数组
        BOOL isSearch = NO;
        for (NSString *str in dbArray) {
            if ([textField.text isEqualToString:str]) {
                isSearch = YES;
            }
        }
        // 判断是否 已经搜索过,并保存到 数据库当中
        if (isSearch) {
        }else{
            if (![_db executeUpdate:@"insert into SearchHistoryList(history) values(?)",textField.text]) {
                NSLog(@"插入数据失败");
            }
        }
        [self hideBoxViewToSearchDataWithSearchString:textField.text];
    }
    //  移除 searchNavigationView
    [self.searchNavigationView removeFromSuperview];
    self.searchNavigationView = nil;
    // 回收键盘
    [textField resignFirstResponder];
    return YES;
}
- (void)textFieldDidBeginEditing:(UITextField *)textField{
    textField.returnKeyType = UIReturnKeySearch;
// 添加对应 视图
    // 判断 当前 scorollView的偏移量, 提取tableView,提取boxView
    CGFloat num = _scrollView.contentOffset.x / kScreenWidth;
    GSSearchViewController_TableView *tableView = (GSSearchViewController_TableView *)[_scrollView viewWithTag:1000 + num];
    UIScrollView *scrollView = [self duplicate:tableView.boxView];
    // 为 复制出来的 view上的button添加方法
    for (UIButton *button in scrollView.subviews) {
        if ([button isMemberOfClass:[UIButton class]]) {
            [button addTarget:self action:@selector(copyButtonAciton:) forControlEvents:(UIControlEventTouchUpInside)];
        }
    }

    scrollView.tag = 111;
    scrollView.hidden = NO;
// 添加 scrollview
    // 改变scrollView的 frame, 因为要添加到 父视图上
    [scrollView setFrame:CGRectMake(0, 0, kScreenWidth,self.searchNavigationView.scrollView.height - 216)];
    
    [self.searchNavigationView.scrollView addSubview:scrollView];
// 添加 searchNavigationView
    [self.view addSubview:self.searchNavigationView];
}
#pragma mark--------------复制视图上button的点击方法-------------
- (void)copyButtonAciton:(UIButton *)button{
    for (UILabel *label in button.subviews) {
        if ([label isMemberOfClass:[UILabel class]]) {
            _textField.text = label.text;
            [self textFieldShouldReturn:_textField];
        }
    }

}

#pragma mark--------------searchNavigationView懒加载-----------
- (GSSearchViewNavigationView *)searchNavigationView{
    if (!_searchNavigationView) {
        _searchNavigationView = [[GSSearchViewNavigationView alloc] initWithFrame:CGRectMake(_navigationView.left, _navigationView.top, _navigationView.width, kScreenHeight - _navigationView.top)];
        
        __weak GSSearchViewController *mySelf = self;
        _searchNavigationView.cellSelected = ^void(NSString *searchingStr){
        
            mySelf.textField.text = searchingStr;
            [mySelf textFieldShouldReturn:mySelf.textField];
        };
        
    }
    return _searchNavigationView;
}


#pragma mark----------------复制View--------------------
- (UIScrollView *)duplicate:(UIScrollView *)view
{
    NSData * tempArchive = [NSKeyedArchiver archivedDataWithRootObject:view];
    return [NSKeyedUnarchiver unarchiveObjectWithData:tempArchive];
}
#pragma mark---------------------------------------------
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
